import React from 'react';
import _ from 'lodash';
import { useTablePipeline, features } from 'ali-react-table';

import { TjTable } from '@/pages/ETrade/components/index.js';

export default ({ queryForm, queryUrlForm, stations, tableData, tableHead }: any) => {
  const [openKeys, onChangeOpenKeys]: any = React.useState([1]);

  // 处理表头
  const getColumns = (columsValue: any[]) => {
    const columns: any[] = [];
    // 添加表格第一列标题
    columns.push({
      name: '交易单元',
      align: 'left',
      code: 'name',
      width: 130,
      lock: true,
    });

    const parentNames: any[] = Object.keys(_.groupBy(columsValue, 'parentName'));
    parentNames.forEach((item: string) => {
      //未定义父元素
      if (item == 'undefined') {
        columsValue.forEach((t: any) => {
          if (!t.parentName) {
            columns.push({
              name: t.name,
              align: 'center',
              width: 120,
              code: t.field,
              render: (value: any) => value ?? '-',
            });
          }
        });
        return;
      }
      columns.push({
        name: item,
        align: 'center',
        children: [],
      });
    });

    columns.forEach((colItem: any, index: number) => {
      const children: any[] = [];
      columsValue.forEach((item: any) => {
        if (colItem.name == item.parentName) {
          children.push({
            name: item.name,
            align: 'center',
            width: 100,
            code: item.field,
            render: (value: any) => value ?? '-',
          });
        }
      });
      columns[index].children = children;
    });
    return columns;
  };

  const dataTable = _.cloneDeep(tableData);
  const [dataSource] = React.useState(dataTable);
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: dataSource, columns: getColumns(tableHead) })
    .primaryKey('id')
    .use(
      features.treeMode({
        openKeys,
        onChangeOpenKeys,
        indentSize: 20,
        iconIndent: 5,
      }),
    );
  return (
    <TjTable
      style={{
        '--header-bgcolor': '#434749',
        '--header-color': 'white',
        '--border-color': 'rgba(255, 255, 255, 0.1)',
        '--header-row-height': '36px',
        '--font-size': '12px',
        '--cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
        '--header-cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
        '--bgcolor': '#222629',
        '--color': 'white',
        '--hover-bgcolor': '#222629',
        '--cell-padding': '4px 5px',
        marginLeft: '24px',
        border: '1px solid #444',
        borderRadius: '5px',
      }}
      useOuterBorder={true}
      stickyScrollHeight={10}
      useVirtual={{ horizontal: true, vertical: true, header: false }}
      {...pipeline.getProps()}
    />
  );
};
